<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 警告区域 -->
      <el-row>
        <el-alert
          show-icon
          title="注意：只允许为第三级分类设置相关参数！"
          type="warning"
          :closable="false"
        >
        </el-alert>
      </el-row>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <span>选择商品分类：</span>
        <!-- 级联 -->
        <el-cascader
          clearable
          v-model="selectOptions"
          :options="cateList"
          @change="handleChange"
          placeholder="请选择"
          :props="{
            expandTrigger: 'hover',
            value: 'cat_id',
            label: 'cat_name',
            children: 'children',
          }"
          ref="cascaderRef"
        ></el-cascader>
      </el-row>
      <!-- tab页签区域 -->
      <el-row class="params_tab">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 添加动态参数面板 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button
              :disabled="isBtnDisabled"
              type="primary"
              size="mini"
              @click="setAddDialogVisible = true"
              >添加参数</el-button
            >
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <!--展开行      -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- {{ $log(scope) }} -->
                  <!-- 渲染动态属性标签 -->
                  <el-tag
                    closable
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    @close="handleCloseOnElTag(i, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <!-- 添加动态属性标签 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 展开行结束 -->
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="isBtnDisabled"
                    @click="showEditDialog(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    :disabled="isBtnDisabled"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态属性面板 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button
              :disabled="isBtnDisabled"
              type="primary"
              size="mini"
              @click="setAddDialogVisible = true"
              >添加属性</el-button
            >
            <!-- 静态参数表格 -->
            <el-table :data="onlyTableData" border stripe>
              <!--展开行      -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- {{ $log(scope) }} -->
                  <!-- 渲染静态属性标签 -->
                  <el-tag
                    closable
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    @close="handleCloseOnElTag(i, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <!-- 添加静态属性标签 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 展开行结束 -->
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="属性名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="isBtnDisabled"
                    @click="showEditDialog(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    :disabled="isBtnDisabled"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeParams(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>

    <!-- 添加对话框 添加参数和添加属性共用同一个对话框 
    需要用到计算属性实现 -->
    <el-dialog
      :title="'添加' + getTitleText"
      :visible.sync="setAddDialogVisible"
      width="50%"
      @close="closedAddDialog"
    >
      <el-form
        :model="addForm"
        :rules="addRuleForm"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        @close="closedAddDialog"
      >
        <el-form-item :label="getTitleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedAddDialog">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + getTitleText"
      :visible.sync="setEditDialogVisible"
      width="50%"
      @close="closedEditDialog"
    >
      <el-form
        :model="editForm"
        :rules="editRuleForm"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
        @close="closedEditDialog"
      >
        <el-form-item :label="getTitleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedEditDialog">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

    

<script>
export default {
  created() {
    this.getCategoriesList()
  },
  data() {
    return {
      //商品分类数据
      cateList: [],
      //选中分类的value 这边我们的value是cat_id
      selectOptions: [],
      //当前激活的tab
      activeName: 'many',
      //动态参数数据
      manyTableData: [],
      //静态参数数据
      onlyTableData: [],
      //控制添加对话框的显示与隐藏
      setAddDialogVisible: false,
      addForm: {
        attr_name: '',
      },
      addRuleForm: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editForm: {},
      editRuleForm: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //控制修改对话框的显示与隐藏
      setEditDialogVisible: false,
      //控制添加动态属性input输入框的显示与隐藏
      inputVisible: false,
      //文本框中的输入值
      inputValue: '',
    }
  },
  methods: {
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) return

      this.cateList = res.data
      //console.log(this.cateList)
    },
    //级联选项值发生改变触发事件
    handleChange() {
      if (this.selectOptions.length > 0) {
        this.getParamsData()
      }
      //console.log(this.selectOptions)
    },
    //tab页签的点击事件
    handleClick() {
      //只有当级联选项选中最后一个分类才去获取参数列表数据
      if (this.selectOptions.length > 0) {
        this.getParamsData()
      }

      //console.log(this.activeName)
    },
    //获取参数数据
    async getParamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.getCatId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }

      //获取res.data中attr_vals动态属性值
      //该值是一个字符串需要转换为数组再拿来渲染
      res.data.forEach((item) => {
        //这里不能直接将attr_vals字符串转为数组
        //因为其他参数里我们并没有attr_vals值是个空''
        //如果对空字符串进行分割得到一个空字符串数组['']
        //那么在循环渲染el-tag组件时会渲染出一个空字符串的el-tag
        //这就不是我们想要的 所以加个三元判断 空字符串给个空数组即可
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //console.log(this.attrValsList)

        //独立添加动态属性标签的inputVisible和inputValue
        //否则会出现多个展开行共用该标签的Boolean和文本框输入值
        item.inputValue = ''
        item.inputVisible = false
      })
      //根据当前激活的页签来给予数据
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.info('请检查数据是否填写无误')
        }

        const { data: res } = await this.$http.post(
          `categories/${this.getCatId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }

        this.$message.success('添加成功')
        this.getParamsData()
        this.setAddDialogVisible = false
      })
    },
    //关闭添加参数对话框
    closedAddDialog() {
      this.setAddDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    //弹出修改参数对话框
    async showEditDialog(attr_id) {
      //console.log(attr_id)
      this.setEditDialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.getCatId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error('查询参数失败')
      }

      this.editForm = res.data
    },

    //修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.info('请检查数据是否填写无误')
        }

        const { data: res } = await this.$http.put(
          `categories/${this.getCatId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }

        this.$message.success('修改成功')
        this.getParamsData()
        this.setEditDialogVisible = false
      })
    },
    //关闭修改对话框
    closedEditDialog() {
      this.setEditDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    //删除参数确认框
    async removeParams(attr_id) {
      //categories/:id/attributes/:attrid
      const confirmResult = await this.$confirm(
        `此操作将永久删除该参数, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      //如果用户确认删除 返回值为confirm 反之 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.getCatId}/attributes/${attr_id}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }

      this.$message.success('删除参数成功')

      this.getParamsData()
    },
    //当文本框失去焦点或按键enter被按下时触发
    async handleInputConfirm(row) {
      //this.inputVisible = !this.inputVisible
      //当用户没有输入有效值 直接隐藏文本框清空内容返回
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }

      //处理用户有效输入值
      //在这里已经将用户添加的数据渲染到页面上并保存
      //所以后续发起请求后 不用再去重新请求参数列表渲染页面
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //发起请求 将数据持久化到后台
      this.saveAttrVals(row)
    },
    //显示文本输入框
    showInput(row) {
      row.inputVisible = true
      //console.log(row.inputVisible)
      //让文本框自动获得焦点
      //$nextTick该实例方法是在当前页面元素
      //重新渲染之后才会调用回调函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //将对attr_vals操作保存到服务器上
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCatId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' '),
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error('修改参数失败')
      }

      this.$message.success('修改参数成功')
    },
    //处理标签的关闭事件
    handleCloseOnElTag(i, row) {
      //删除对应标签的参数
      row.attr_vals.splice(i, 1)
      //在服务器上保存删除后的数据
      this.saveAttrVals(row)
    },
  },
  computed: {
    //用来动态控制按钮的禁用与否
    isBtnDisabled() {
      //console.log(this.selectOptions.length)
      if (this.selectOptions.length > 0) {
        return false
      }
      return true
    },
    //获取最后一级商品分类的ID
    getCatId() {
      if (this.selectOptions.length > 0) {
        //console.log(this.selectOptions[this.selectOptions.length - 1])
        return this.selectOptions[this.selectOptions.length - 1]
      }

      return null
    },

    getTitleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>
<style lang="less" scoped>
.cat_opt,
.params_tab {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>